import { STORAGE_KEY_USER_INFU } from '@/consts/consts'
import type { IUser } from '@oBiz/interface'
import { getGlobalState, setGlobalState } from '../globalStore'
import { apiGetUserInfo, getUserInfo } from './apis'

window.addEventListener('storage', ({ key, newValue }) => {
  if (key !== STORAGE_KEY_USER_INFU) return
  setGlobalState({ userInfo: newValue ? getUserInfo(newValue) : null })
})

type IUserInfo = IUser

let pendingPromise: Promise<IUserInfo> | null = null

/** 获取用户信息（整个页面会话只会发一次请求，重复调用只会取已有结果或缓存的 pendingPromise） */
const fetchUserInfo = async (): Promise<IUserInfo> => {
  const { userInfo } = getGlobalState()
  if (userInfo) return userInfo // 已有结果
  if (pendingPromise) return pendingPromise.then() // 请求中

  pendingPromise = apiGetUserInfo()
    .then(data => {
      pendingPromise = null
      setGlobalState({ userInfo: data })
      return data
    })
    .catch(err => {
      pendingPromise = null
      throw err
    })

  return pendingPromise.then()
}

export type { IUserInfo }
export { fetchUserInfo }
